﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Admin.NET.Application;

/// <summary>
/// 消息通知表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AppNotificationService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<AppNotification> _appNotificationRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly UserManager _userManager;

    public AppNotificationService(SqlSugarRepository<AppNotification> appNotificationRep, ISqlSugarClient sqlSugarClient, UserManager userManager)
    {
        _appNotificationRep = appNotificationRep;
        _sqlSugarClient = sqlSugarClient;
        _userManager= userManager;
    }

    /// <summary>
    /// 分页查询消息通知表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询消息通知表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AppNotificationOutput>> Page(PageAppNotificationInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appNotificationRep.AsQueryable()
            //.Where(u => u.ReceiverId == _userManager.UserId)
            .WhereIF(input.ReceiverId != null, u => u.ReceiverId == input.ReceiverId)
            .WhereIF(input.SenderId != null, u => u.SenderId == input.SenderId)
            .WhereIF(input.Type.HasValue, u => u.Type == input.Type)
            .LeftJoin<SysUser>((u, receiver) => u.ReceiverId == receiver.Id)
            .LeftJoin<SysUser>((u, receiver, sender) => u.SenderId == sender.Id)
            .LeftJoin<AppVehiclePurchase>((u, receiver, sender, purchase) => u.PurchaseId == purchase.Id)
            .LeftJoin<AppVehicleInfo>((u, receiver, sender, purchase, b) => u.BidId == b.Id)
            .LeftJoin<AppVehicleBrand>((u, receiver, sender, purchase, b, vb) => purchase.BrandId == vb.Id)
            .LeftJoin<AppVehicleModel>((u, receiver, sender, purchase, b, vb, vm) => purchase.ModelId == vm.Id)
            .Select((u, receiver, sender, purchase, b, vb, vm) => new AppNotificationOutput
            {
                Id = u.Id,
                ReceiverId = u.ReceiverId,
                ReceiverFkDisplayName = $"{receiver.RealName}",
                SenderId = u.SenderId,
                SenderAvatar = sender.Avatar,
                SenderFkDisplayName = $"{sender.RealName}",
                PurchaseId = u.PurchaseId,
                PurchaseFkDisplayName = $"{purchase.Id}-{purchase.BrandId}",
                BidId = u.BidId,
                BFkDisplayName = $"{vb.Name}",
                ModelName= vm.Name,
                Type = u.Type,
                Title = u.Title,
                Content = u.Content,
                IsRead = u.IsRead,
                ReadTime = u.ReadTime,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        var result = await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
        foreach (var item in result.Items)
        {
            item.TypeName = item.Type.GetDescription();
        }
        return result;
    }

    /// <summary>
    /// 获取消息通知表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取消息通知表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<AppNotification> Detail([FromQuery] QueryByIdAppNotificationInput input)
    {
        return await _appNotificationRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加消息通知表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加消息通知表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAppNotificationInput input)
    {
        var entity = input.Adapt<AppNotification>();
        return await _appNotificationRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新消息通知表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新消息通知表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAppNotificationInput input)
    {
        var entity = input.Adapt<AppNotification>();
        await _appNotificationRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除消息通知表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除消息通知表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAppNotificationInput input)
    {
        var entity = await _appNotificationRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _appNotificationRep.FakeDeleteAsync(entity);   //假删除
        //await _appNotificationRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除消息通知表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除消息通知表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteAppNotificationInput> input)
    {
        var exp = Expressionable.Create<AppNotification>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _appNotificationRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _appNotificationRep.FakeDeleteAsync(list);   //假删除
        //return await _appNotificationRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataAppNotificationInput input)
    {
        var receiverIdData = await _appNotificationRep.Context.Queryable<SysUser>()
            .InnerJoinIF<AppNotification>(input.FromPage, (u, r) => u.Id == r.ReceiverId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.RealName}"
            }).ToListAsync();
        var senderIdData = await _appNotificationRep.Context.Queryable<SysUser>()
            .InnerJoinIF<AppNotification>(input.FromPage, (u, r) => u.Id == r.SenderId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.RealName}"
            }).ToListAsync();
        var purchaseIdData = await _appNotificationRep.Context.Queryable<AppVehiclePurchase>()
            .InnerJoinIF<AppNotification>(input.FromPage, (u, r) => u.Id == r.PurchaseId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.Id}-{u.BrandId}"
            }).ToListAsync();
        var bidIdData = await _appNotificationRep.Context.Queryable<AppVehicleInfo>()
            .InnerJoinIF<AppNotification>(input.FromPage, (u, r) => u.Id == r.BidId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.BrandId}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "receiverId", receiverIdData },
            { "senderId", senderIdData },
            { "purchaseId", purchaseIdData },
            { "bidId", bidIdData },
        };
    }
    
    /// <summary>
    /// 导出消息通知表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出消息通知表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageAppNotificationInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportAppNotificationOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "消息通知表导出记录");
    }
    
    /// <summary>
    /// 下载消息通知表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载消息通知表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAppNotificationOutput>(), "消息通知表导入模板", (_, info) =>
        {
            if (nameof(ExportAppNotificationOutput.ReceiverFkDisplayName) == info.Name) return _appNotificationRep.Context.Queryable<SysUser>().Select(u => $"{u.RealName}").Distinct().ToList();
            if (nameof(ExportAppNotificationOutput.SenderFkDisplayName) == info.Name) return _appNotificationRep.Context.Queryable<SysUser>().Select(u => $"{u.RealName}").Distinct().ToList();
            if (nameof(ExportAppNotificationOutput.PurchaseFkDisplayName) == info.Name) return _appNotificationRep.Context.Queryable<AppVehiclePurchase>().Select(u => $"{u.Id}-{u.BrandId}").Distinct().ToList();
            if (nameof(ExportAppNotificationOutput.BFkDisplayName) == info.Name) return _appNotificationRep.Context.Queryable<AppVehicleInfo>().Select(u => $"{u.BrandId}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入消息通知表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入消息通知表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportAppNotificationInput, AppNotification>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 接收用户ID
                    var receiverIdLabelList = pageItems.Where(x => x.ReceiverFkDisplayName != null).Select(x => x.ReceiverFkDisplayName).Distinct().ToList();
                    if (receiverIdLabelList.Any()) {
                        var receiverIdLinkMap = _appNotificationRep.Context.Queryable<SysUser>().Where(u => receiverIdLabelList.Contains($"{u.RealName}")).ToList().ToDictionary(u => $"{u.RealName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ReceiverId = receiverIdLinkMap.GetValueOrDefault(e.ReceiverFkDisplayName ?? "");
                            if (e.ReceiverId == null) e.Error = "接收用户ID链接失败";
                        });
                    }
                    // 链接 发送用户ID
                    var senderIdLabelList = pageItems.Where(x => x.SenderFkDisplayName != null).Select(x => x.SenderFkDisplayName).Distinct().ToList();
                    if (senderIdLabelList.Any()) {
                        var senderIdLinkMap = _appNotificationRep.Context.Queryable<SysUser>().Where(u => senderIdLabelList.Contains($"{u.RealName}")).ToList().ToDictionary(u => $"{u.RealName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.SenderId = senderIdLinkMap.GetValueOrDefault(e.SenderFkDisplayName ?? "");
                            if (e.SenderId == null) e.Error = "发送用户ID链接失败";
                        });
                    }
                    // 链接 关联的求购ID
                    var purchaseIdLabelList = pageItems.Where(x => x.PurchaseFkDisplayName != null).Select(x => x.PurchaseFkDisplayName).Distinct().ToList();
                    if (purchaseIdLabelList.Any()) {
                        var purchaseIdLinkMap = _appNotificationRep.Context.Queryable<AppVehiclePurchase>().Where(u => purchaseIdLabelList.Contains($"{u.Id}-{u.BrandId}")).ToList().ToDictionary(u => $"{u.Id}-{u.BrandId}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.PurchaseId = purchaseIdLinkMap.GetValueOrDefault(e.PurchaseFkDisplayName ?? "");
                            if (e.PurchaseId == null) e.Error = "关联的求购ID链接失败";
                        });
                    }
                    // 链接 关联的竞拍ID
                    var bidIdLabelList = pageItems.Where(x => x.BFkDisplayName != null).Select(x => x.BFkDisplayName).Distinct().ToList();
                    if (bidIdLabelList.Any()) {
                        var bidIdLinkMap = _appNotificationRep.Context.Queryable<AppVehicleInfo>().Where(u => bidIdLabelList.Contains($"{u.BrandId}")).ToList().ToDictionary(u => $"{u.BrandId}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.BidId = bidIdLinkMap.GetValueOrDefault(e.BFkDisplayName ?? "");
                            if (e.BidId == null) e.Error = "关联的竞拍ID链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.ReceiverId == null){
                            x.Error = "接收用户ID不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Type == null){
                            x.Error = "消息类型不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<AppNotification>>();
                    
                    var storageable = _appNotificationRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Title), "消息标题不能为空")
                        .SplitError(it => it.Item.Title?.Length > 100, "消息标题长度不能超过100个字符")
                        .SplitError(it => it.Item.Content?.Length > 500, "消息内容长度不能超过500个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
